import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import authApi from '../api/auth';

interface UserProfile {
  id: number;
  gender: string | null;
  avatar: string;
  address: string | null;
  email: string | null;
  userId: number;
  nickName: string;
  age: number | null;
}

interface UserInfo {
  id: number;
  username: string;
  profile: UserProfile;
  roles?: Array<{
    id: number;
    name: string;
    code: string;
  }>;
  currentRole?: {
    id: number;
    name: string;
    code: string;
  };
}

export const useAuth = () => {
  const navigate = useNavigate();
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [showUserMenu, setShowUserMenu] = useState(false);

  // 检查登录状态并获取用户信息
  const checkLoginStatus = async () => {
    const token = localStorage.getItem('token');
    console.log('=== 检查登录状态 ===');
    console.log('Token:', token ? '存在' : '不存在');
    
    if (token) {
      try {
        console.log('正在调用API获取用户信息...');
        const response = await authApi.getUser();
        console.log('API响应:', response);
        
        if (response && response.data) {
          console.log('用户信息获取成功:', response.data);
          setIsLoggedIn(true);
          setUserInfo(response.data);
          localStorage.setItem('userInfo', JSON.stringify(response.data));
        } else {
          console.log('API调用成功但没有数据，可能token已过期');
          handleLogout();
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        handleLogout();
      }
    } else {
      console.log('没有token，设置为未登录状态');
      setIsLoggedIn(false);
      setUserInfo(null);
    }
    setLoading(false);
  };

  // 退出登录
  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    setIsLoggedIn(false);
    setUserInfo(null);
    setShowUserMenu(false);
    navigate('/login');
  };

  // 获取用户显示名称
  const getUserDisplayName = () => {
    if (!userInfo) return '用户';
    return userInfo.profile?.nickName || userInfo.profile?.name || userInfo.username || '用户';
  };

  // 获取用户头像首字母
  const getUserAvatarLetter = () => {
    if (!userInfo) return 'U';
    const name = userInfo.profile?.nickName || userInfo.profile?.name || userInfo.username;
    return name ? name.charAt(0) : 'U';
  };

  // 获取用户头像URL
  const getUserAvatar = () => {
    return userInfo?.profile?.avatar || '';
  };

  // 初始化
  useEffect(() => {
    checkLoginStatus();
  }, []);

  return {
    isLoggedIn,
    userInfo,
    loading,
    showUserMenu,
    setShowUserMenu,
    handleLogout,
    getUserDisplayName,
    getUserAvatarLetter,
    getUserAvatar,
    checkLoginStatus
  };
};